package com.luke.xiaotiaowa.component;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.URLUtil;
import com.luke.xiaotiaowa.DynamicSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * 动态权限数据源，用于获取动态权限规则
 * 
 * @author xiaotiaowa
 * @create 2023/3/24
 */
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> configAttributeMap = null;
    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    public void clearDataSource() {
        configAttributeMap.clear();
        configAttributeMap = null;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        if (MapUtil.isEmpty(configAttributeMap)) {
            this.loadDataSource();
        }
        var configAttributes = new ArrayList<ConfigAttribute>();
        //获取当前访问的路径
        var url = ((FilterInvocation) o).getRequestUrl();
        var path = URLUtil.getPath(url);
        var pathMatcher = new AntPathMatcher();
        //获取访问该路径所需资源
        for (String pattern : configAttributeMap.keySet()) {
            for (String pat: pattern.split(",")) {
                if (pathMatcher.match(pat, path)) {
                    configAttributes.add(configAttributeMap.get(pattern));
                }
            }
        }
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
